<template>
    <div class="CarUser-container content-wrapper">
        <div class="filter-container">
            <el-form :model="listQuery" :inline="true" ref="filterForm" style="display: inline-block">
                <el-form-item prop="username" class="filter-item">
                    <el-input v-model="listQuery.username" placeholder="用户名" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item prop="orderBy" class="filter-item">
                    <el-select v-model="listQuery.orderBy" placeholder="排序" style="width: 150px">
                        <el-option
                                v-for="item in sortOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
                <el-button class="filter-item" type="primary" icon="mars-reset" @click="handleResetFilter">重置
                </el-button>

                <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="plus"@click="handleCreate()">添加</el-button>
                <el-dropdown class="filter-item margin-left-10" trigger="click" @command="command">
                    <el-button type="primary">
                        更多操作<i class="el-icon-caret-bottom el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown" style="width: 200px;">
                        <el-dropdown-item command="locked">锁定账号</el-dropdown-item>
                        <el-dropdown-item command="unlocked">解锁账号</el-dropdown-item>
                        <el-dropdown-item command="ResetPassword">重置密码</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-form>
        </div>

        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间"
                  @selection-change="handleSelectionChange"
                  border fit highlight-current-row
                  style="width: 100%">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column label="ID" width="65" align="center">
                <template slot-scope="scope"> {{scope.row.id}} </template>
            </el-table-column>

            <el-table-column label="城市" width="100px" align="center">
                <template slot-scope="scope"> {{scope.row.city}} </template>
            </el-table-column>
            <el-table-column label="区域" width="100px" align="center">
                <template slot-scope="scope"> {{scope.row.area}} </template>
            </el-table-column>
            <el-table-column label="姓名" width="100px" align="center">
                <template slot-scope="scope"> {{scope.row.realname}} </template>
            </el-table-column>
            <el-table-column label="性别" width="100px" align="center">
                <template slot-scope="scope"> {{scope.row.gender | sexFilter}} </template>
            </el-table-column>
            <el-table-column label="用户名" width="100px" align="center">
                <template slot-scope="scope"> {{scope.row.username}} </template>
            </el-table-column>
            <el-table-column label="手机号码" width="130px" align="center">
                <template slot-scope="scope"> {{scope.row.mobile}} </template>
            </el-table-column>
            <el-table-column label="电子邮箱" width="200px" align="center">
                <template slot-scope="scope"> {{scope.row.email}} </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status | statusTagFilter">{{scope.row.status | statusFilter}}</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>
            <el-table-column label="更新时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="操作" width="180px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>

                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" size="tiny"
                   @close="handleCloseDialog">
            <el-form :model="form" :rules="rules" ref="form" labelPosition="right" labelWidth="80px"
                     style="width: 400px">
                <el-form-item label="城市" prop="city">
                    <el-input v-model="form.city"></el-input>
                </el-form-item>

                <el-form-item label="区域" prop="area">
                    <el-input v-model="form.area"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="realname">
                    <el-input v-model="form.realname"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="form.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="form.mobile"></el-input>
                </el-form-item>
                <el-form-item label="电子邮件" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="2">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="form.remarks">
                    </el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import { created, deleted, updated, fetchObject, fetchList, updateAccountStatus, resetPassword } from '@/api/tukuan/user'

    const sortOptions = [{label: '按ID升序', key: 'id asc'}, {label: '按ID降序', key: 'id desc'}]

    export default {
        name: 'CarUser',
        data() {
            return {
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    rows: 10,
                    username: undefined,
                    orderBy: 'id asc'
                },
                sortOptions,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                multipleSelection: [],
                form: {
                    city: '',
                    area: '',
                    realname: '',
                    gender: 1,
                    username: '',
                    mobile: '',
                    email: '',
                    status: 1,
                    remarks: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    code: [
                        { required: true, message: '请输入唯一表示', trigger: 'blur' }
                    ]
                }

            }
        },
        created() {
            this.getList()
        },
        filters: {
            sexFilter(sex) {
                const sexArray = ['男', '女', '未知']
                return sexArray[sex?--sex:'']
            },
            statusFilter(status) {
                const statusArray = ['正常', '锁定']
                return statusArray[status?--status:'']
            },
            statusTagFilter(status) {
                const statusArray = ['success', 'danger']
                return statusArray[status?--status:'']
            }
        },
        methods: {
            command(command) {
                if(command === 'ResetPassword') {
                    this.handleResetPassword()
                } else if(command === 'locked') {
                    this.handleLocked(2)
                } else if(command === 'unlocked') {
                    this.handleLocked(1)
                }
            },
            handleLocked(status) {
                if(this.multipleSelection.length > 0) {
                    const ids = []
                    for(var item of this.multipleSelection) {
                        ids.push(item.id)
                    }
                    updateAccountStatus({ids: ids.join(','), status: status}).then(response => {
                        this.list = response.data.list
                        this.total = response.data.total
                        this.listLoading = false
                    }).catch((error)=>{
                        console.log(error)
                        this.listLoading = false
                    })

                } else {
                    this.$message({
                        message: '请选择需要锁定的用户',
                        type: 'warning', duration: 2000
                    })
                }
            },
            handleResetPassword() {
                if(this.multipleSelection.length > 0) {
                    const ids = []
                    for(var item of this.multipleSelection) {
                        ids.push(item.id)
                    }
                    resetPassword({ids: ids.join(','), status: status}).then(response => {
                        this.list = response.data.list
                        this.total = response.data.total
                        this.listLoading = false
                    }).catch((error)=>{
                        console.log(error)
                        this.listLoading = false
                    })

                } else {
                    this.$message({
                        message: '请选择需要锁定的用户',
                        type: 'warning', duration: 2000
                    })
                }
            },
            getList() {
                this.listLoading = true
                fetchList(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoading = false
                })
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleResetFilter() {
                this.$refs.filterForm.resetFields()
                this.getList()
            },
            handleCreate() {
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {
                this.dialogStatus = 'update'

                fetchObject(row.id).then(response => {
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                })
            },
            handleDelete(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getList()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })

            },
            update() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            resetForm() {
                this.$refs['form'].resetFields()
                this.form = {
                    city: '',
                    area: '',
                    realname: '',
                    gender: 1,
                    username: '',
                    mobile: '',
                    email: '',
                    status: 1,
                    remarks: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>